/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_orm.htm
 *
 * Zhiqim Orm is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.orm.executor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.zhiqim.kernel.model.maps.MapSO;
import org.zhiqim.kernel.model.maps.MapSS;
import org.zhiqim.kernel.util.Closes;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.ORMServer;
import org.zhiqim.orm.datasource.ZResultSet;
import org.zhiqim.orm.datasource.ZStatement;
import org.zhiqim.orm.exception.TableNotExistException;

/**
 * 查询处理器接口，参数为MapSO类型，结果集为基本类型[int,long,String,Object]
 * 
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class QueryExecutorMapBase implements QueryExecutor
{
    /**
     * 执行executeQuery处理
     * 
     * @param server        ORM服务
     * @param conn          数据库连接
     * @param sql           ZSQL语句
     * @param param         参数
     * @param replaceMap    可替换表
     * @return              返回结果集列表
     * @throws ORMException 映射异常
     */
    public List<?> execute(ORMServer server, Connection conn, String sql, Class<?> resultClass, Object param, MapSS replaceMap) throws ORMException
    {
        PreparedStatement pstmt = null;
        ResultSet rst = null;
        String str = null;

        try
        {
            // 1.替换可替换符$$
            sql = Sqls.formatReplaceMap(sql, replaceMap);
            Map<?, ?> paramMap = (param instanceof MapSO) ? ((MapSO) param).instance() : (Map<?, ?>) param;

            // 替换通配符##为?
            List<String> paramKeyList = new ArrayList<>();
            sql = ZStatement.paramMapString(sql, paramKeyList);

            // SQL语句处理完毕
            if (server.isQuerySqlLog())
                str = sql;

            pstmt = conn.prepareStatement(sql);
            for (int i=0;i<paramKeyList.size();i++)
            {
                String paramKey = paramKeyList.get(i);
                Object paramValue = paramMap.get(paramKey);
                if (server.isQuerySqlLog())
                    str = ZStatement.setParameter(server, pstmt, i + 1, paramValue, str);
                else
                    ZStatement.setParameter(server, pstmt, i + 1, paramValue);
            }

            // 查询可以打印SQL
            if (server.isQuerySqlLog())
            {
                str = str.replaceAll("-%6-%-3%-", "?");
                qSqlLog.info(str);
            }

            rst = pstmt.executeQuery();

            //解决结果集到基础对象中
            return ZResultSet.parseToBase(rst, resultClass);
        }
        catch (SQLException e) 
        {
            if (server.getPolicy().isTableNotExist(e))
                throw new TableNotExistException("[%s][%s]", e, e.getMessage(), sql);
            else
                throw new ORMException("[%s][%s]", e, e.getMessage(), sql);
        }
        catch (Throwable e)
        {
            throw new ORMException("[%s][%s]", e, e.getMessage(), sql);
        }
        finally
        {
            Closes.closeIgnoreException(rst, pstmt);
        }
    }
}
